﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WPF.Zero
{
    public class PasswordBehavior : Behavior<PasswordBox>
    {
        protected override void OnAttached()
        {
            AssociatedObject.PasswordChanged += AssociatedObject_PasswordChanged;
            base.OnAttached();
        }

        protected override void OnDetaching()
        {
            AssociatedObject.PasswordChanged -= AssociatedObject_PasswordChanged;
            base.OnDetaching();
        }

        private void AssociatedObject_PasswordChanged(object sender, RoutedEventArgs e)
        {
            //当密码框的Password值发生变化时，去更新附加属性Password的值
            var passwordBox = sender as PasswordBox;
            string password = PasswordExtension.GetPassword(passwordBox);

            if (passwordBox != null && password != passwordBox.Password)
            {
                PasswordExtension.SetPassword(passwordBox, passwordBox.Password);
            }
        }

    }

    public  class PasswordExtension:Behavior<PasswordBox>
    {
       
        public static string GetPassword(DependencyObject obj)
        {
            return (string)obj.GetValue(PasswordProperty);
        }

        public static void SetPassword(DependencyObject obj, string value)
        {
            obj.SetValue(PasswordProperty, value);
        }

        public static readonly DependencyProperty PasswordProperty = 
            DependencyProperty.RegisterAttached("Password", typeof(string ), typeof(PasswordExtension), new PropertyMetadata(null));

        public static void PropertyChangedCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            //当附加属性PassWord发生变化时，去更新附加属性对象上的密码框本来的Password值
            var passwordBox = d as PasswordBox;

            string password= (string)e.NewValue;

            if (passwordBox != null && passwordBox.Password != password)
            {
                passwordBox.Password = password;
            }
            
        }
    }
}
